package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.mvc.PageView;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.utils.StringUtils;
import net.starwifi.duobao.utils.times.DateTool;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Controller - member.
 *
 * @author ruoo
 * @version 1.0
 */
@Controller("adminMemberController")
@RequestMapping("/member")
public class MemberController extends BaseController {

    @Autowired
    MemberService memberService;

    @Autowired
    private ServletContext servletContext;

    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model) {
        return "/member/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Member member, RedirectAttributes redirectAttributes) {
        if (!isValid(member)) {
            return ERROR_VIEW;
        }
        Member dbMember=memberService.findByUsername(member.getUsername());
        if(dbMember!=null){
            return ERROR_VIEW;
        }
        Member db2Member=memberService.findByUsername(member.getUsername());
        if(db2Member!=null){
            return ERROR_VIEW;
        }
        member.setBalance(BigDecimal.ZERO);
        member.setVirtualCurrency(BigDecimal.ZERO);
        member.setCurrencyBalance(BigDecimal.ZERO);
        String salt= StringUtils.getUUID();
        String pass=DigestUtils.md5Hex(member.getPassword() + salt);
        member.setPassword(pass);
        member.setSalt(salt);
        member.setLoginFailureCount(Integer.bitCount(0));
        member.setLockedDate(null);
        member.setGender(0);
        memberService.save(member);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list";
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("entity", memberService.find(id));
        return "/member/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Member member, RedirectAttributes redirectAttributes) {
        Member pMember=memberService.find(member.getId());
        if (member.getPassword()==null) {
            member.setSalt(pMember.getSalt());
            member.setPassword(pMember.getPassword());
        } else {
            String salt= StringUtils.getUUID();
            String pass=DigestUtils.md5Hex(member.getPassword() + salt);
            member.setSalt(salt);
            member.setPassword(pass);
        }
        memberService.update(member, "currencyBalance","virtualCurrency","balance","username","gender","loginFailureCount","lockedDate","loginDate");
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageView pageView, ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        pageView.addOrder(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        model.addAttribute("currentDate",format.format(new Date()));
        Date beginData= DateTool.setHms(new Date(), 0, 0, 0);
        Date endData= DateTool.setHms(new Date(),23,59,59);
        model.addAttribute("beginData", beginData);
        model.addAttribute("endData", endData);
        model.addAttribute("page", memberService.getScrollData(pageView));
        return "/member/list";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public @ResponseBody
    Message delete(Long[] ids) {
        memberService.delete(ids);
        return SUCCESS_MESSAGE;
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/recharge", method = RequestMethod.GET)
    public String recharge(Long id, ModelMap model) {
        model.addAttribute("entity", memberService.find(id));
        return "/member/recharge";
    }

    /**
     * 导出Excel
     * */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public String  exportExcel(PageView pageView,HttpServletRequest request,ModelMap model) throws IOException {
        pageView.filterQuery(request);
        pageView.getOrders().add(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String url=memberService.exportExcel2003WithUsermodel(format.format(new Date()), servletContext.getRealPath("/"), pageView);
        model.addAttribute("message","Excel生成成功");
        model.addAttribute("content","<a href='/"+url+"' target=\"_blank\">点击下载</a>");
        return "/common/handle";
    }
}
